package com.shanghaionstar.report.model;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.google.gson.Gson;
import com.onstar.cn.common.BuildConfig;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.sqlite.entities.RequestEventReportEntity;
import com.onstar.cn.framework.mvp.base.core.NetworkUtil;
import com.onstar.cn.mag.enumtype.OSType;
import com.shanghaionstar.enumtype.OSTypeEnum;
import com.shanghaionstar.report.bean.ClientDTO;
import com.shanghaionstar.report.bean.DeviceDTO;
import com.shanghaionstar.report.bean.DynamicDTO;
import com.shanghaionstar.report.bean.EventDTO;
import com.shanghaionstar.report.bean.ExtensionDTO;
import com.shanghaionstar.report.bean.LocationDTO;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.report.bean.TraceDTO;
import com.shanghaionstar.report.bean.UserDTO;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.NavHolder;
import com.tencent.android.tpush.XGPushConfig;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by 6335yz on 2016/11/8.
 */
public class ReportModel {
    public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

//    /**
//     * 默认固定content的report
//     *
//     * @param context
//     * @return
//     */
//    public TraceDTO getTraceDTO(Context context, ReportReqParam reportReqParam) {
//        ExtraDTO extraDTO = new ExtraDTO();
//        List<ExtraItem> extraItems = new ArrayList<>();
//        ExtraItem latExtra = new ExtraItem();
//        latExtra.setCode("latitude");
//        latExtra.setValue(String.valueOf(reportReqParam.latitude));
//        extraItems.add(latExtra);
//
//        ExtraItem lonExtra = new ExtraItem();
//        lonExtra.setCode("longitude");
//        lonExtra.setValue(String.valueOf(reportReqParam.longitude));
//        extraItems.add(lonExtra);
//
//        ExtraItem errExtra = new ExtraItem();
//        errExtra.setCode("error");
//        errExtra.setValue(String.valueOf(reportReqParam.error));
//        extraItems.add(errExtra);
//
//        extraDTO.setExtraItems(extraItems);
//        String extraJson = JsonUtils.toJson(extraDTO);
//
//        TraceDTO traceDTO = new TraceDTO();
//        traceDTO.setClient(new ClientDTO.ClientBuilder()
//                .clientID(ApplicationUtil.getInstance().getSubscriberID())
//                .clientType(OSType.ANDROID.value())
//                .clientSecretKey("123")
//                .clientVersion("" + BuildConfig.VERSION_CODE)
//                .createClientDTO());
//        traceDTO.setChannelID(reportReqParam.channelId);
//        DynamicDTO dynamicDTO = new DynamicDTO();
//        dynamicDTO.setEvent(new EventDTO.EventBuilder()
//                .description("123")
//                .endTimestamp(new Date())
//                .extra(extraJson)
//                .functionID(reportReqParam.functionNameFindId)
//                .language(DeviceUtil.getLanguage())
//                .objectID(reportReqParam.objectID)
//                .objectType(reportReqParam.objectType)
//                .operation(reportReqParam.operationType)
//                .result(reportReqParam.result)
//                .startTimestamp(new Date())
//                .tag("")
//                .timestamp(new Date())
//                .type(reportReqParam.type)
//                .creatEventDTO());
//        dynamicDTO.setLocation(new LocationDTO.LocationBuilder()
//                .address("")
//                .currentIP(getLocalIpAddress(context))
//                .latitude(NavHolder.getInstance(context).getMyLocation() == null ? 0 :
//                        NavHolder.getInstance(context).getMyLocation().getLatitude())
//                .longitude(NavHolder.getInstance(context).getMyLocation() == null ? 0 :
//                        NavHolder.getInstance(context).getMyLocation().getLongitude())
//                .createLocationDTO());
//        dynamicDTO.setSpanID("1");
//        dynamicDTO.setTraceID("1");
//        dynamicDTO.setUser(new UserDTO.UserBuilder()
//                .accountID(ApplicationUtil.getInstance().getAccountId())
//                .email(ApplicationUtil.getInstance().getEmail())
//                .guid("")
//                .role(ApplicationUtil.getInstance().getLoginRole())
//                .mobile(ApplicationUtil.getInstance().getMobile())
//                .subscriberID(ApplicationUtil.getInstance().getSubscriberID())
//                .userID(ApplicationUtil.getInstance().getIdpID())
//                .vin(ApplicationUtil.getInstance().getVin()
//                .createUserDTO());
//        List<DynamicDTO> dynamicDTOs = new ArrayList<>();
//        dynamicDTOs.add(dynamicDTO);
//
//        traceDTO.setDatas(dynamicDTOs);
//        traceDTO.setTimestamp(new Date());
//        traceDTO.setDevice(new DeviceDTO.DeviceBuilder()
//                .deviceDesc("")
//                .deviceID(new DeviceUtil(context).getDeviceID())
//                .deviceToken(XGPushConfig.getToken(context))
//                .deviceType(DeviceUtil.getDeviceType())
//                .deviceOS(OSTypeEnum.ANDROID.value())
//                .createDeviceDTO());
//        return traceDTO;
//    }


    /**
     * 默认固定content的report
     *
     * @param context
     * @return
     */
    public DynamicDTO getDynamicDTO(Context context, ReportReqParam reportReqParam) {
        ExtensionDTO extensionLatDTO = new ExtensionDTO();
        extensionLatDTO.setCode("latitude");
        extensionLatDTO.setValue(String.valueOf(reportReqParam.latitude));

        ExtensionDTO extensionLonDTO = new ExtensionDTO();
        extensionLonDTO.setCode("longitude");
        extensionLonDTO.setValue(String.valueOf(reportReqParam.longitude));

        ExtensionDTO extensionErrLonDTO = new ExtensionDTO();
        extensionErrLonDTO.setCode("error");
        extensionErrLonDTO.setValue(String.valueOf(reportReqParam.error));

        List<ExtensionDTO> extra = new ArrayList<>();
        extra.add(extensionLatDTO);
        extra.add(extensionLonDTO);
        extra.add(extensionErrLonDTO);


        DynamicDTO dynamicDTO = new DynamicDTO();
        dynamicDTO.setEvent(new EventDTO.EventBuilder()
                .description("")
                .endTimestamp(reportReqParam.endTimestamp)
                .extra(extra)
                .functionID(reportReqParam.functionNameFindId)
                .language(DeviceUtil.getLanguage())
                .objectID(reportReqParam.objectID)
                .objectType(reportReqParam.objectType)
                .operation(reportReqParam.operationType)
                .result(reportReqParam.result)
                .startTimestamp(reportReqParam.startTimestamp)
                .tag("")
                .timestamp(System.currentTimeMillis())
                .type(reportReqParam.type)
                .creatEventDTO());
        dynamicDTO.setLocation(new LocationDTO.LocationBuilder()
                .address("")
                .currentIP(getLocalIpAddress(context))
                .latitude(NavHolder.getInstance(context).getMyLocation() == null ? 0 :
                        NavHolder.getInstance(context).getMyLocation().getLatitude())
                .longitude(NavHolder.getInstance(context).getMyLocation() == null ? 0 :
                        NavHolder.getInstance(context).getMyLocation().getLongitude())
                .network(NetworkUtil.checkNetworkInfo(context) == NetworkUtil.WIFI ? 1 : 0)
                .createLocationDTO());
        dynamicDTO.setSpanID("");
        dynamicDTO.setTraceID("");
        dynamicDTO.setUser(new UserDTO.UserBuilder()
                .accountID(ApplicationUtil.getInstance().getAccountId())
                .email(ApplicationUtil.getInstance().getEmail())
                .guid("")
                .role(ApplicationUtil.getInstance().getLoginRole())
                .mobile(ApplicationUtil.getInstance().getMobile())
                .subscriberID(ApplicationUtil.getInstance().getSubscriberID())
                .userID(ApplicationUtil.getInstance().getIdpID())
                .vin(ApplicationUtil.getInstance().getVin())
                .createUserDTO());
        return dynamicDTO;
    }


    private String getLocalIpAddress(final Context context) {
        int status = NetworkUtil.checkNetworkInfo(context);
        switch (status) {
            case NetworkUtil.MOBILE:
                return getGPRSLocalIpAddress();
            case NetworkUtil.WIFI:
                return getWIFILocalIpAdress(context);
            case NetworkUtil.NO_CONNECT:
                return "";
        }
        return "";
    }

    private static String getGPRSLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }

    private String getWIFILocalIpAdress(Context mContext) {
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = formatIpAddress(ipAddress);
        return ip;
    }

    private String formatIpAddress(int ipAdress) {

        return (ipAdress & 0xFF) + "." +
                ((ipAdress >> 8) & 0xFF) + "." +
                ((ipAdress >> 16) & 0xFF) + "." +
                (ipAdress >> 24 & 0xFF);
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF);
    }

    /**
     * 预留,看需求是否要给时间做格式化
     *
     * @param pattern
     * @return
     */
    private String getDateFromPattern(String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = new Date();
        return format.format(date);
    }


    public TraceDTO getAdaptReport(List<RequestEventReportEntity> listdata, Context mContext) {
        Context context = mContext.getApplicationContext();
        List<DynamicDTO> dynamicDTOs = new ArrayList<>();
        for (RequestEventReportEntity entity : listdata) {
            dynamicDTOs.add(new Gson().fromJson(entity.getContent(), DynamicDTO.class));
        }
        TraceDTO traceDTO = new TraceDTO();
        traceDTO.setClient(new ClientDTO.ClientBuilder()
                .clientID(ApplicationUtil.getInstance().getSubscriberID())
                .clientType(OSType.ANDROID.value())
                .clientSecretKey("123")
                .clientVersion("" + BuildConfig.VERSION_CODE)
                .createClientDTO());
        traceDTO.setChannelID("0");

        traceDTO.setDatas(dynamicDTOs);
        traceDTO.setTimestamp(System.currentTimeMillis());
        traceDTO.setDevice(new DeviceDTO.DeviceBuilder()
                .deviceDesc("")
                .deviceID(new DeviceUtil(context).getDeviceID())
                .deviceToken(XGPushConfig.getToken(context))
                .deviceType(DeviceUtil.getDeviceType())
                .deviceOS(OSTypeEnum.ANDROID.value())
                .createDeviceDTO());
        return traceDTO;
    }
}
